package com.killers.cold.model;

import com.alibaba.fastjson.JSON;
import com.killers.cold.exception.IErrorCodeType;

import java.io.Serializable;

/**
 * 统一结果返回
 * @param <T>
 */
public class Result<T> implements Serializable {

    private static final String DEFAULT_SUCCESS_MESSAGE = "Success";
    public static final String CODE_FORMAT = "%d-%d-%s";
    private static final long serialVersionUID = 1L;
    private String code;
    private String message;
    private String cause;
    private T data;

    public String getCode() {
        return code;
    }

    public Result setCode(String code) {
        this.code = code;
        return this;
    }

    public String getMessage() {
        return message;
    }

    public Result setMessage(String message) {
        this.message = message;
        return this;
    }

    public String getCause() {
        return cause;
    }

    public Result setCause(String cause) {
        this.cause = cause;
        return this;
    }

    public T getData() {
        return data;
    }

    public Result setData(T data) {
        this.data = data;
        return this;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    public static Result genSuccessResult(Object data) {
        return new Result()
                .setCode("0")
                .setMessage(DEFAULT_SUCCESS_MESSAGE)
                .setData(data);
    }

    public static Result genFailResult(String appId, IErrorCodeType errorCodeType, String cause) {
        return new Result()
                .setCode(formatCode("客户端错误", errorCodeType.getCode(), appId))
                .setMessage(errorCodeType.getMessage())
                .setCause(cause);
    }

    public static Result geFailResult(String appId, int code, String message, String cause) {
        return new Result()
                .setCode(formatCode("客户端错误", code, appId))
                .setMessage(message)
                .setCause(cause);
    }

    public static Result genErrorResult(String appId, int code, String message, String cause) {
        return new Result()
                .setCode(formatCode("服务端错误", code, appId))
                .setMessage(message)
                .setCause(cause);
    }

    public static Result genErrorResult(String appId, IErrorCodeType errorCodeType, String cause) {
        return new Result()
                .setCode(formatCode("服务端错误", errorCodeType.getCode(), appId))
                .setMessage(errorCodeType.getMessage())
                .setCause(cause);
    }

    public static String formatCode(String exceptionType, int code, String appId) {
        return String.format(CODE_FORMAT, exceptionType, code, appId);
    }

}
